<?php

/**
 * api 接口控制器
 *
 * @author pufan
 */

namespace Portal\Controller;

use Think\Controller;

class ApiBaseController extends Controller{
    
    function _initialize() {
        if ($this->isWeixin() == FALSE ) {
            $this->api_return(403, 'Forbidden');
        }
    }
    /*
     *  限制从微信摇一摇进入
     */
    protected function checkShake() {
        $userShakeTs = S('shake_event_ts:'.$_SESSION['open_id']);

        if ($userShakeTs == FALSE) {
            $shakeTimeOutUrl = U('Portal/Index/shakeTimeout');
            $this->api_return(504, '您在摇一摇内停留时间过长,请从微信摇一摇重新进入', 0, 'jumpUrl', $shakeTimeOutUrl);
        }
    }
    
    protected function isWeixin(){
        $agent = strtolower($_SERVER['HTTP_USER_AGENT']);

        $is_weixin = strpos($agent, 'micromessenger') ? true : false ;  
        if($is_weixin){
            return true;
        }else{
            return false;
        }
    }
        
    protected function api_return($errcode = 0, $errmsg = 'ok', $status = '', $data_name = '', $data = array()) {
        $json_data['errcode'] = $errcode;
        $json_data['errmsg'] = $errmsg;
        if ($errcode) {
            if ($data_name) {
                $json_data[$data_name] = $data;
            }
            \Think\Log::record('query_string: '.$_SERVER['QUERY_STRING'].' '.'api_return:'. $errcode.' openid: '.$_SESSION['open_id']);
            $this->ajaxReturn($json_data);
        }
        if ($data_name) {
            $json_data['data'] = array('status' => $status, $data_name => $data);
        } else {
            $json_data['data'] = array('status' => $status);
        }
        \Think\Log::record('query_string: '.$_SERVER['QUERY_STRING'].' args:'.json_encode($_POST).' '.'api_return:'. json_encode($json_data).' openid: '.$_SESSION['open_id']);
        $this->ajaxReturn($json_data);
    }
}

